<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <p>监听数据变化时的注意事项</p>
    <p>1. 数组</p>
    <p>1.1 通过下标修改数组的一整项</p>
    <p>vm.arr1[0] = {name:'vivo', price: 6666}修改完整的一项，全部修改，无法监听</p>
    <p v-for="phone in arr1">{{phone.name}} -- {{phone.price}}</p>
    <button @click="changeArr1">正确答案</button>
    <p>1.2 通过length直接修改数组长度</p>
    <button @click="changeArr2">正确答案</button>
    <p>2. 对象</p>
    <p>2.1新增对象属性</p>
    <p v-for="(val, key, index) in obj">{{index + 1}}. {{key}}: {{val}}</p>
    <button @click="changeObj1">正确答案</button>
    <p>2.1删除对象属性</p>
    <button @click="changeObj2">正确答案</button>
  </div>
  <script src="../vue.js"></script>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        arr1: [
          {name: 'iphone', price: 6999},
          {name: 'xiaomi', price: 5999},
          {name: 'huawei', price: 4999},
        ],
        obj: {
          name: 'Jack',
          age: 18,
          job: 'stu'
        }
      },
      methods: {
        changeArr1() {
          // 错误方式 this.arr1[1] = {xxx}
          // splice三个参数：修改的位置，修改的长度，新的内容
          // 原生js的方式：this.arr1.splice(0, 1, {name: "vivo", price: 6666})
          // vue的方式
          Vue.set(this.arr1, 0, {name: "vivo", price: 6666})
          // Vue.set的别名：this.$set(this.arr1, 0, {name: "vivo", price: 6666})
        },
        changeArr2() {
          // 错误方式this.arr1.length = 1
          this.arr1.splice(1);
        },
        // 新增对象属性
        changeObj1() {
          // 错误方式:this.obj.xx=xx;
          // Vue.set(this.obj, 'sex', 'boy');
          this.$set(this.obj, 'sex', 'boy')
        },
        // 删除对象属性
        changeObj2() {
          // 错误方式: delete this.obj.xx;
          this.$delete(this.obj, 'age');
        }
      },
    })
  </script>
</body>
</html>